﻿using MySql.Data.MySqlClient;
using RsaRegister;
using RsaRegister.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace SoftRegManager.BLL
{
    public partial class GreatBLL
    {
        public string ErrMsg { get; private set; }
        private ISqlSugarClient mDbClient;
        public GreatBLL(string connStr, SqlSugar.DbType dbType)
        {
           
            var config = new ConnectionConfig()
            {
                
                ConnectionString = connStr,
                DbType = dbType,//设置数据库类型
                IsAutoCloseConnection = true,//自动释放数据务，如果存在事务，在事务结束后释放
                InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
            };
            mDbClient = new SqlSugarClient(config);
#if DEBUG
            //用来打印Sql方便调式    
            mDbClient.Aop.OnLogExecuting = (sql, pars) =>
            {
                Debug.WriteLine(sql + "\r\n" +
                mDbClient.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                Debug.WriteLine("");
            };
#endif
            
        }
        #region 数据库维护
        public bool DbReady
        {
            get
            {
                return mDbClient.DbMaintenance.IsAnyTable("SoftInfo");
            }
        }
        /// <summary>
        /// 使用CodeFirst 方式生成表
        /// 一般用于系统初始化
        /// </summary>
        /// <returns></returns>
        public void CreateTables()
        {
            mDbClient.CodeFirst.BackupTable().InitTables(typeof(RegInfo),  typeof(SoftInfo));
        }
        public List<DbTableInfo> GetTables()
        {
            return mDbClient.DbMaintenance.GetTableInfoList();
        }
        public List<DbColumnInfo> GetDbColumnInfos(string tableName)
        {
            return mDbClient.DbMaintenance.GetColumnInfosByTableName(tableName);
        }
        public bool DropTables()
        {
            var tables = GetTables();
            bool sus = true;
            foreach (var table in tables)
            {
                sus &= mDbClient.DbMaintenance.DropTable(table.Name);
            }
            return sus;
        }
       
        #endregion

    }
}
